#!/usr/bin/python
# --coding:utf-8--


# 1. 获取所有li标签
from lxml import etree
html = etree.parse('case_demo.html')
print(type(html))  # 显示etree.parse() 返回类型
result = html.xpath('//li')
print(result)  # 打印<li>标签的元素集合
for res in result:
    print(etree.tostring(res))
print("=====================1==============================")

# 2. 获取所有li元素下的所有class属性的值
from lxml import etree
html = etree.parse('case_demo.html')
result = html.xpath('//li/@class')
print(result)
print("=======================2============================")

# 3. 获取li标签下href为 https://www.dushu.com/lianzai/1115_5.html 的a标签
from lxml import etree
html = etree.parse('case_demo.html')
result = html.xpath('//li/a[@href="https://www.dushu.com/lianzai/1115_5.html"]')
print(result)
for res in result:
    print(etree.tostring(res))
print("======================3=============================")

# 4. 获取li标签下所有span标签
from lxml import etree
html = etree.parse('case_demo.html')
# result = html.xpath('//li/span')
# 注意这么写是不对的：
# 因为 / 是用来获取子元素的，而 <span> 并不是 <li> 的子元素，所以，要用双斜杠
result = html.xpath('//li//a')
print(result)
print("========================4===========================")

# 5. 获取li标签下的a标签里的所有class
from lxml import etree
html = etree.parse('case_demo.html')
result = html.xpath('//li/a//@href')
print(result)
print("=======================5============================")

# 6. 获取最后一个li的a的href属性对应的值
from lxml import etree
html = etree.parse('case_demo.html')
result = html.xpath('//li[last()]/a/@href')  # 如果想获取HTML中全部链接，则去掉[last()]
# 谓语 [last()] 可以找到最后一个元素
print(result)
print("=======================6============================")

# 7. 获取倒数第二个li元素的内容
from lxml import etree
html = etree.parse('case_demo.html')
result = html.xpath('//li[last()-1]/a')
# text方法可以获取元素内容
print(result[0].text)
print("=======================7===========================")

# 8. 获取倒数第二个li元素的内容的第二种方法
from lxml import etree
html = etree.parse('case_demo.html')
result = html.xpath('//li[last()-1]/a/text()')
print(result)

